package com.sr.service.impl;

import com.sr.dao.RoleDao;
import com.sr.dao.UserDao;
import com.sr.dao.UserRoleDao;
import com.sr.enums.ResponseCode;
import com.sr.exception.BusinessException;
import com.sr.ibase.impl.BaseServiceImpl;
import com.sr.pojo.SysUser;
import com.sr.pojo.SysUserRole;
import com.sr.service.IUserService;
import com.sr.util.ToolUtil;
import com.sr.vo.req.UserOwnRoleReqVo;
import com.sr.vo.req.UserPasswordReqVo;
import com.sr.vo.req.UserReqVo;
import com.sr.vo.resp.UserOwnRoleRespVo;
import com.sr.vo.resp.UserRespVo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xiaochi
 * @date 2022/5/2 21:01
 * @desc UserServiceImpl
 */
@Service
@RequiredArgsConstructor(onConstructor = @__)
public class UserServiceImpl extends BaseServiceImpl<SysUser> implements IUserService {

    private final UserDao userDao;
    private final RoleDao roleDao;
    private final UserRoleDao userRoleDao;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    @Override
    public SysUser getUserByUserName(String username) {
        return this.findOne(SysUser.builder().username(username).build());
    }

    /**
     * 查询用户拥有的角色数据接口
     * @param userId
     * @return
     */
    @Override
    public UserOwnRoleRespVo getUserOwnRole(String userId) {
        List<SysUserRole> userRoles = userRoleDao.select(SysUserRole.builder().userId(userId).build());
        UserOwnRoleRespVo respVo = new UserOwnRoleRespVo();
        respVo.setOwnRoleIds(userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
        respVo.setAllRole(roleDao.selectAll());
        return respVo;
    }

    /**
     * 更新用户角色
     * @param reqVo
     * @return
     */
    @Override
    public int setUserOwnRole(UserOwnRoleReqVo reqVo) {
        // 先删除用户原来的拥有的角色id
        int result = userRoleDao.delete(SysUserRole.builder().userId(reqVo.getUserId()).build());
        if (reqVo.getRoleIds().isEmpty()){
            return result;
        }
        // 批量插入用户角色数据
        List<SysUserRole> list = new ArrayList<>();
        Date date = new Date();
        for (String roleId : reqVo.getRoleIds()){
            SysUserRole userRole = new SysUserRole();
            userRole.setId(ToolUtil.nextId());
            userRole.setUserId(reqVo.getUserId());
            userRole.setRoleId(roleId);
            userRole.setCreateTime(date);
            list.add(userRole);
        }
        return userRoleDao.insertList(list);
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    @Override
    public int resetUpdatePassword(String userId) {
        SysUser sysUser = this.findOne(userId);
        if (Objects.isNull(sysUser)){
            throw new BusinessException(ResponseCode.DATA_ERROR);
        }
        sysUser.setPassword(bCryptPasswordEncoder.encode("123456"));
        return this.updateById(sysUser);
    }

    /**
     * 更新用户
     * @param reqVo
     * @param userId
     * @return
     */
    @Override
    public int updateUserInfo(UserReqVo reqVo, String userId) {
        SysUser sysUser = ToolUtil.copy(reqVo, SysUser.class);
        sysUser.setId(userId);
        sysUser.setUpdateId(userId);
        sysUser.setUpdateTime(new Date());
        if (StringUtils.isEmpty(reqVo.getPassword())){
            sysUser.setPassword(null);
        }else {
            sysUser.setPassword(bCryptPasswordEncoder.encode(reqVo.getPassword()));
        }
        return this.updateById(sysUser);
    }

    /**
     * 批量/删除用户
     * @param ids
     * @param userId
     * @return
     */
    @Override
    public int deletedUsers(List<String> ids, String userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUpdateId(userId);
        sysUser.setUpdateTime(new Date());
        return userDao.deletedUsers(sysUser,ids);
    }

    /**
     * 用户详情
     * @param userId
     * @return
     */
    @Override
    public UserRespVo detailInfo(String userId) {
        return ToolUtil.copy(this.findOne(userId),UserRespVo.class);
    }

    /**
     * 保存个人信息
     * @param sysUser
     * @param userId
     * @return
     */
    @Override
    public int userUpdateDetailInfo(SysUser sysUser, String userId) {
        sysUser.setId(userId);
        sysUser.setUpdateId(userId);
        return this.updateById(sysUser);
    }

    /**
     * 修改个人密码
     * @param reqVo
     * @param userId
     * @return
     */
    @Override
    public int userUpdatePassword(UserPasswordReqVo reqVo, String userId) {
        SysUser sysUser = this.findOne(userId);
        if (sysUser == null){
            throw new BusinessException(ResponseCode.TOKEN_ERROR);
        }
        sysUser.setId(userId);
        sysUser.setUpdateId(userId);
        sysUser.setPassword(bCryptPasswordEncoder.encode(reqVo.getNewPwd()));
        sysUser.setUpdateTime(new Date());
        return this.updateById(sysUser);
    }
}
